/*
 * MIT License
 *
 * Copyright (c) 2023-present, tangli
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

@file:JvmName("MyBatisPlus")

/**
 * daoExtension
 *
 * @author tangli
 * @date 2022/07/13 19:10
 */

package tony.mybatis.utils

import com.baomidou.mybatisplus.core.conditions.Wrapper
import com.baomidou.mybatisplus.core.toolkit.Constants
import com.fasterxml.jackson.core.type.TypeReference
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Proxy
import java.lang.reflect.Type
import java.util.concurrent.ConcurrentHashMap
import org.apache.ibatis.annotations.Param
import org.apache.ibatis.mapping.MappedStatement
import tony.core.model.PageQuery
import tony.core.model.PageResult
import tony.core.utils.annotation
import tony.core.utils.asToNotNull
import tony.core.utils.isTypesOrSubTypesOf
import tony.core.utils.rawClass
import tony.mybatis.dao.BaseDao
import tony.mybatis.wrapper.query.TonyChainQuery

@get:JvmSynthetic
internal val DAO_ENTITY_CLASS_MAP = ConcurrentHashMap<Class<*>, Class<*>>()

@get:JvmSynthetic
internal val CLASS_NAME_DAO_CLASS = ConcurrentHashMap<String, Class<*>>()

/**
 * 实际类别
 * @author tangli
 * @date 2023/09/28 19:54
 */
@JvmSynthetic
internal fun <T : Any> BaseDao<T>.actualClass() =
    if (!Proxy.isProxyClass(this::class.java)) {
        this::class.java
    } else {
        this::class.java
            .genericInterfaces
            .first {
                it
                    .rawClass()
                    .isTypesOrSubTypesOf(BaseDao::class.java)
            }.rawClass()
    }

/**
 * 获取entityClass
 * @return [Class]<[T]>
 * @author tangli
 * @date 2023/09/28 19:53
 */
@JvmSynthetic
internal fun <T : Any> BaseDao<T>.getEntityClass(): Class<T> =
    DAO_ENTITY_CLASS_MAP
        .getOrPut(this::class.java) {
            actualClass().typeParamOfSuperInterface(BaseDao::class.java).rawClass()
        }.asToNotNull()

/**
 * 获取接口的泛型参数
 * @param [type] 类型
 * @param [index] 类型位置, 默认第一个
 * @return [Type]
 * @author tangli
 * @date 2023/09/13 19:28
 */
internal fun Class<*>.typeParamOfSuperInterface(
    type: Class<*>,
    index: Int = 0,
): Type {
    val genericInterfaces = this.genericInterfaces
    val matchedInterface =
        genericInterfaces.firstOrNull {
            it.rawClass().name == type.typeName
        } ?: throw IllegalStateException("$this does not implement the $type")
    check(matchedInterface !is Class<*>) { "${matchedInterface.typeName} constructed without actual type information" }
    return matchedInterface.asToNotNull<ParameterizedType>().actualTypeArguments[index]
}

/**
 * 通过[MappedStatement] 获取对应的 mapper/dao [Class]
 * @return [Class]<*>
 * @author tangli
 * @date 2025/09/15 10:17
 */
public fun MappedStatement.mapperClass(): Class<*> =
    CLASS_NAME_DAO_CLASS
        .getOrPut(id) {
            Class.forName(this.id.take(this.id.lastIndexOf('.')))
        }

/**
 * 通过[MappedStatement] 获取对应的 mapper/dao 方法 [Method]
 * @return [Method] mapper/dao 方法
 * @author tangli
 * @date 2025/09/15 10:17
 */
public fun MappedStatement.mapperMethod(): Method? =
    mapperClass()
        .methods
        .firstOrNull { method ->
            method.name.equals(id.substring(id.lastIndexOf('.') + 1, id.length))
        }

/**
 * 通过[MappedStatement] 获取对应的 mapper/dao 方法 [Method] 的 注解[A]
 * @return [A] 注解
 * @author tangli
 * @date 2025/09/15 10:17
 */
public fun <A : Annotation> MappedStatement.mapperMethodAnnotation(annotationType: Class<A>): A? =
    mapperMethod()?.annotation(annotationType)

/**
 * 根据 entity 条件，查询全部记录, 并转为 [R] 类型
 * @param queryWrapper  实体对象封装操作类（可以为 null）
 * @author tangli
 * @date 2023/09/28 19:54
 */
public inline fun <T : Any, reified R> BaseDao<T>.selectListTo(queryWrapper: Wrapper<T>?): List<R> =
    selectList(queryWrapper, object : TypeReference<R>() {})

/**
 * 分页查询出全局统一结构. 并转为 [R] 类型
 * @param [page] 页
 * @param [queryWrapper] 查询包装器
 * @return [PageResult]<[T]>
 * @author tangli
 * @date 2023/09/13 19:39
 */
public inline fun <T : Any, reified R> BaseDao<T>.selectPageResultTo(
    page: PageQuery<*>?,
    @Param(Constants.WRAPPER) queryWrapper: Wrapper<T>?,
): PageResult<R> =
    selectPageResult(page, queryWrapper, object : TypeReference<R>() {})

/**
 * 列表查询, 再转为 [R]
 * @return [List]<[R]>
 * @author tangli
 * @date 2023/11/22 19:23
 */
public inline fun <T : Any, reified R> TonyChainQuery<T>.listTo(): List<R> =
    baseMapper.selectList(wrapper, object : TypeReference<R>() {})

/**
 * 分页查询出全局统一结构, 再转为 targetType [R]
 * @param [page] 全局统一请求分页结构.
 * @return [PageResult]<[T]>
 * @author tangli
 * @date 2023/10/23 19:49
 */
public inline fun <T : Any, reified R> TonyChainQuery<T>.pageResultTo(page: PageQuery<*>?): PageResult<R> =
    baseMapper.selectPageResult(page, wrapper, object : TypeReference<R>() {})
